//
//  PrescriptionOrderDetailController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2021/8/11.
//  Copyright © 2021 QDSG. All rights reserved.
//

import UIKit

class PrescriptionOrderDetailController: BaseViewController {
    
    var updateClosure: (() -> ())?
    
    private var viewModel = PrescriptionOrderDetailViewModel(mode: .detail)
    
    convenience init(orderId: String) {
        self.init()
        self.viewModel.orderId = orderId
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "订单详情"
        
        loadData()
    }
    
    override func makeUI() {
        super.makeUI()
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalTo(view.safeAreaLayoutGuide).priority(.low)
            make.bottom.equalToSuperview()
        }
        
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(bottomSafeH + 50)
        }
    }
    
    override func bindViewModel() {
        super.bindViewModel()
        
        viewModel.updateClosure = { [weak self, viewModel] in
            self?.tableView.reloadData()
            self?.bottomView.bind(to: viewModel)
        }
        
        viewModel.changeClosure = { [weak self] in
            self?.loadData()
            self?.updateClosure?()
        }
    }
    
    private func loadData() {
        viewModel.getPrescriptionOrderDetail()
    }
    
    private lazy var bottomView: PrescriptionOrderStatusBottomView = {
        let view = UINib.loadViewFrom(PrescriptionOrderStatusBottomView.self)
        view.backgroundColor = .white
        view.delegate = self
        return view
    }()

    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: bottomSafeH + 50, right: 0)
        tableView.backgroundColor = .background
        tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 1))
        tableView.tableFooterView = UIView()
        tableView.separatorStyle = .none
        
        tableView.delegate = self
        tableView.dataSource = self
        
        tableView.register(PrescriptionOrderPatientInfoDetailCell.nibForCell(),
                           forCellReuseIdentifier: PrescriptionOrderPatientInfoDetailCell.reuseIdentifier())
        tableView.register(PrescriptionOrderMedicalRecordNoDetailCell.nibForCell(),
                           forCellReuseIdentifier: PrescriptionOrderMedicalRecordNoDetailCell.reuseIdentifier())
        tableView.register(PrescriptionOrderDrugsListCell.nibForCell(),
                           forCellReuseIdentifier: PrescriptionOrderDrugsListCell.reuseIdentifier())
        tableView.register(PrescriptionOrderDoctorInfoDetailCell.nibForCell(),
                           forCellReuseIdentifier: PrescriptionOrderDoctorInfoDetailCell.reuseIdentifier())
        tableView.register(PrescriptionOrderStatusDetailCell.nibForCell(),
                           forCellReuseIdentifier: PrescriptionOrderStatusDetailCell.reuseIdentifier())
        
        return tableView
    }()

}

// MARK: - PrescriptionOrderStatusBottomViewDelegate

extension PrescriptionOrderDetailController: PrescriptionOrderStatusBottomViewDelegate {
    func pay(_ view: PrescriptionOrderStatusBottomView) {
        func pushOrderPayVC(with orderId: String) {
            let orderStatusVc = PrescriptionOrderPayController(orderId: orderId)
            removeCurrentVcWhenPush(orderStatusVc)
        }
        
        pushOrderPayVC(with: viewModel.orderId)
    }
    
    func cancel(_ view: PrescriptionOrderStatusBottomView) {
        func cancelOrder(_ action: UIAlertAction) {
            changeOrderStatus(.canceled)
        }
        
        AlertTool.showAlert(self, title: "取消订单", message: "您确定要取消订单吗？", sureTitle: "确定", cancelTitle: "再想想", type: .double, sureHandler: cancelOrder)
    }
    
    func applyRefund(_ view: PrescriptionOrderStatusBottomView) {
        func applyRefund(_ action: UIAlertAction) {
            changeOrderStatus(.applyRefund)
        }
        
        AlertTool.showAlert(self, title: "申请退药", sureTitle: "确定", cancelTitle: "取消", type: .double, sureHandler: applyRefund)
    }
    
    func checkLogistics(_ view: PrescriptionOrderStatusBottomView) {
        let vc = PrescriptionOrderLogisticsController(with: viewModel.expressNum)
        navigationController?.pushViewController(vc, animated: true)
    }
    
    func confirmReceive(_ view: PrescriptionOrderStatusBottomView) {
        changeOrderStatus(.completed)
    }
    
    func cancelRefund(_ view: PrescriptionOrderStatusBottomView) {
        func cancel(_ action: UIAlertAction) {}
        
        AlertTool.showAlert(self, title: "取消退药", sureTitle: "确定", cancelTitle: "取消", type: .double, sureHandler: { _ in
            self.changeOrderStatus(.cancelRefund)
        })
    }
    
    func inputExpressNumber(_ view: PrescriptionOrderStatusBottomView) {
        let vc = PrescriptionOrderTrackingNumberController(id: viewModel.prescriptionId)
        navigationController?.pushViewController(vc, animated: true)
        vc.handleClosure = { [weak self] in self?.loadData() }
    }
    
    private func changeOrderStatus(_ status: PrescriptionOrderStatus) {
        viewModel.changePrescriptionOrderStatus(status)
    }
}

// MARK: - UITableViewDataSource

extension PrescriptionOrderDetailController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return viewModel.numberOfSections
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.numberOfRows(in: section)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let viewModel = viewModel.viewModel(at: indexPath.section)
        switch viewModel.mode {
        case .patientInfoForDetail:
            let cell = tableView.dequeueReusableCell(withIdentifier: PrescriptionOrderPatientInfoDetailCell.reuseIdentifier(),
                                                     for: indexPath) as! PrescriptionOrderPatientInfoDetailCell
            cell.bind(to: viewModel)
            return cell
        case .medicalRecordNo:
            let cell = tableView.dequeueReusableCell(withIdentifier: PrescriptionOrderMedicalRecordNoDetailCell.reuseIdentifier(),
                                                     for: indexPath) as! PrescriptionOrderMedicalRecordNoDetailCell
            cell.bind(to: viewModel)
            return cell
        case .drugs:
            let cell = tableView.dequeueReusableCell(withIdentifier: PrescriptionOrderDrugsListCell.reuseIdentifier(),
                                                     for: indexPath) as! PrescriptionOrderDrugsListCell
            cell.bind(to: viewModel)
            return cell
        case .doctorInfoForDetail:
            let cell = tableView.dequeueReusableCell(withIdentifier: PrescriptionOrderDoctorInfoDetailCell.reuseIdentifier(),
                                                     for: indexPath) as! PrescriptionOrderDoctorInfoDetailCell
            cell.bind(to: viewModel)
            return cell
        case .orderStatus:
            let cell = tableView.dequeueReusableCell(withIdentifier: PrescriptionOrderStatusDetailCell.reuseIdentifier(),
                                                     for: indexPath) as! PrescriptionOrderStatusDetailCell
            cell.bind(to: viewModel, at: indexPath)
            return cell
        default:
            return UITableViewCell()
        }
    }
}

// MARK: - UITableViewDelegate

extension PrescriptionOrderDetailController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return viewModel.cellHeight(at: indexPath)
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let viewModel = viewModel.viewModel(at: section)
        switch viewModel.mode {
        case .patientInfoForDetail,
             .medicalRecordNo:   return UIView()
        case .orderStatus:
            let header = UINib.loadViewFrom(PrescriptionOrderStatusSectionHeader.self)
            header.bind(to: viewModel)
            return header
        default:                 return nil
        }
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return viewModel.headerHeight(in: section)
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
}
